<template>
  <div class="box">
    <el-card>
      <el-form :mode="dataMap" label-width="80px">
        <el-row :getter="20">
          <el-col :span="4">
            <el-form-item label="位置">
              <el-input
                type="text"
                clearable
                v-model="dataMap.searchText"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="经度">
              <el-input
                type="text"
                clearable
                v-model="dataMap.lat"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="纬度">
              <el-input
                type="text"
                clearable
                v-model="dataMap.lng"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-button
              type="primary"
              style="margin-left: 12px"
              @click="handleSearch('address')"
            >
              地点查询
            </el-button>
            <el-button
              type="primary"
              style="margin-left: 12px"
              @click="handleSearch('lat')"
            >
              经纬查询
            </el-button>
            <el-button style="margin-left: 12px" @click="initMap()">
              初始化
            </el-button>
          </el-col>
        </el-row>
        <el-row :getter="20">
          <el-col :span="4">
            <el-form-item label="边界线县区">
              <el-select
                clearable
                v-model="dataMap.county"
                placeholder="以菏泽市县区为例"
              >
                <el-option
                  v-for="item in countyList"
                  :key="item.id"
                  :label="item.fullname"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-button
              type="primary"
              style="margin-left: 12px"
              @click="markerPolygon()"
            >
              获取边界线
            </el-button>
            <el-button
              type="danger"
              style="margin-left: 12px"
              @click="markerHeat()"
            >
              展示热力图
            </el-button>
            <el-button
              type="success"
              style="margin-left: 12px"
              @click="markerCar()"
            >
              小车轨迹
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card>
      <div class="mapLayout">
        <div id="mapBox"></div>
        <span class="mapInfo">{{ dataMap.lat }} {{ dataMap.lng }}</span>
      </div>
    </el-card>
  </div>
</template>

<script setup>
  import { onMounted, onUnmounted } from "vue";
  import {
    latLingPOIMap,
    AddressPOIMap,
    getchildrenMap,
  } from "/@/api/modules/map.js";
  import {
    markerCarFn,
    markerPolygonFn,
    markerHeatFn,
    easeToFn,
  } from "./components/mapFn";
  import { ElMessage } from "element-plus";

  /**
   * @var
   */

  let dataMap = ref({
    lat: 35.234309,
    lng: 115.479646,
    zoom: 9,
    searchText: "",
    markerLayer: null,
    map: null,
    polygon: null,
    county: "",
  });

  const countyList = ref([]);

  /**
   * @method
   */
  // 地图初始化
  const initMap = async () => {
    if (window.map) {
      await window.map.destroy();
    }

    var center = new TMap.LatLng(dataMap.value.lat, dataMap.value.lng); //设置中心点坐标

    // //初始化地图
    window.map = new TMap.Map("mapBox", {
      center,
      maptype: "satellite",
      zoom: dataMap.value.zoom,
    });
    //绑定点击事件
    window.map.on("click", function (evt) {
      var lat = evt.latLng.getLat().toFixed(6);
      var lng = evt.latLng.getLng().toFixed(6);
      dataMap.value.lat = lat;
      dataMap.value.lng = lng;
      markerMap();
    });
    markerMap();
  };
  // 重新加载地图
  const initLaton = () => {
    let element = document.getElementById("mapBox");
    if (element.firstChild) element.removeChild(element.firstChild);
    let center = new TMap.LatLng(dataMap.value.lat, dataMap.value.lng); //设置中心点坐标
    window.map = new TMap.Map("mapBox", {
      center,
      zoom: 13,
    });
    // 打点
    markerMap();
  };
  // 标记地图
  const markerMap = () => {
    const { lat, lng } = dataMap.value;
    dataMap.value.markerLayer = new TMap.MultiMarker({
      map: window.map, //指定地图容器
      //样式定义
      styles: {
        //创建一个styleId为"myStyle"的样式（styles的子属性名即为styleId）
        myStyle: new TMap.MarkerStyle({
          width: 25, // 点标记样式宽度（像素）
          height: 35, // 点标记样式高度（像素）
          // src: mapIcon, //图片路径
          //焦点在图片中的像素位置，一般大头针类似形式的图片以针尖位置做为焦点，圆形点以圆心位置为焦点
          anchor: { x: 16, y: 32 },
        }),
      },
      //点标记数据数组
      geometries: [
        {
          id: "1", //点标记唯一标识，后续如果有删除、修改位置等操作，都需要此id
          styleId: "myStyle", //指定样式id
          position: new TMap.LatLng(lat, lng), //点标记坐标位置
          properties: {
            //自定义属性
            title: "marker1",
          },
        },
      ],
    });
  };
  // 画边界线
  const markerPolygon = async () => {
    const { county } = dataMap.value;

    if (!county) {
      ElMessage("边界线县区选择不能为空！");
      return;
    }

    const row = countyList.value.filter((item) => {
      if (item.id == county) return item;
    });

    const { fullname, id, location, polygon } = row[0];

    dataMap.value.lat = location.lat;
    dataMap.value.lng = location.lng;

    // 初始化
    await initMap();

    markerPolygonFn(polygon[0]);
  };
  // 热力图
  const markerHeat = async () => {
    const { county } = dataMap.value;

    if (!county) {
      ElMessage("边界线县区选择不能为空！");
      return;
    }

    const row = countyList.value.filter((item) => {
      if (item.id == county) return item;
    });

    const { fullname, id, location, polygon } = row[0];

    dataMap.value.lat = location.lat;
    dataMap.value.lng = location.lng;

    //初始化地图
    await initMap();

    markerHeatFn(polygon[0]);
  };
  // 小车轨迹
  const markerCar = async () => {
    const { county } = dataMap.value;

    if (!county) {
      ElMessage("边界线县区选择不能为空！");
      return;
    }

    const row = countyList.value.filter((item) => {
      if (item.id == county) return item;
    });

    const { fullname, id, location, polygon } = row[0];

    dataMap.value.lat = location.lat;
    dataMap.value.lng = location.lng;

    //初始化地图
    await initMap();

    markerCarFn(polygon[0]);
  };
  // 平滑跳转
  const easeTo = () => {
    easeToFn(dataMap.value);
  };
  // 关键字搜索
  const handleSearch = async (apiType) => {
    const { lat, lng, searchText } = dataMap.value;

    let res = null;

    if (apiType == "address") {
      if (!searchText) {
        ElMessage("位置不能为空！");
        return;
      }

      const { status, message, result } = await AddressPOIMap({
        address: searchText,
      });

      if (status) {
        ElMessage({
          message,
          type: "warning",
        });
        return;
      }

      const { ad_info, address_components, location } = result;

      dataMap.value.lat = location.lat;
      dataMap.value.lng = location.lng;
    }

    if (apiType == "lat") {
      res = await latLingPOIMap({ location: `${lat},${lng}` });
    }

    console.log(res);
    // 打点
    markerMap();
    // 平滑跳转
    easeTo();
  };
  // 获取位置边界线列表信息【以菏泽市为例】
  const getCountyPolygonList = async () => {
    try {
      let res = await getchildrenMap();
      countyList.value = await res.result[0];
      // 单县为例
      dataMap.value.county = "371722";
      markerPolygon();
    } catch (error) {}
  };

  onMounted(() => {
    initMap();
    getCountyPolygonList();
  });
  // 销毁实例
  onUnmounted(() => {
    window.map.destroy();
    window.map = null;
  });
</script>

<style lang="scss" scoped>
  .box {
    .mapLayout {
      position: relative;
      .mapInfo {
        display: inline-block;
        position: absolute;
        z-index: 66;
        top: 16px;
        left: 16px;
        width: 200px;
        height: 40px;
        line-height: 40px;
        text-align: center;
        background-color: aqua;
        border-radius: 4px;
      }
    }
  }
  .mapBox {
    width: 100%;
    height: 600px;
  }
</style>
